import { t } from 'i18next'
import React, { FC, useRef, useState } from 'react'
import { StyledExtractCodeWrap } from './style'
import { Button, Space, Password } from '@kedacom/react-next'
import { fetchGetPlatformServiceUrl, fetchSetCookie } from '@/api/global'
import { getUrlParams } from '@/utils'
import Header from '@/components/Header'
import useInit from '@/hooks/useInit'
import useStorageEvent from '@/hooks/useStorageEvent'
import { fetchValidExtractCode } from '@/api/extractCode'
import WebRecommendBrowser from '@/components/WebRecommendBrowser'

const meetingMoid = getUrlParams('meetingMoid') ?? ''

const App: FC = () => {
	const [code, setCode] = useState<string>('')
	const [isShowEye, setIsShowEye] = useState(false)
	const [errorMsg, setErrorMsg] = useState<string>('')
	const preUrlRef = useRef<string>('/meeting')
	useInit()
	useStorageEvent()
	const onChange = (value: string) => {
		setCode(value)
	}
	const onOk = async () => {
		//这个是分享的界面，特殊处理
		//跨级建云，由于分享过来，需要先去setCookie，此时不清楚应该是走
		//meeting的还是meetingCore的setCookie，所以需要预请求
		const preUrl = await fetchGetPlatformServiceUrl()
		await fetchSetCookie({
			meeting_moid: meetingMoid,
			type: 1,
		})
		preUrlRef.current = preUrl || '/meeting'
		fetchValidExtractCode(meetingMoid, code).then((data) => {
			if (data) {
				window.location.href = `${preUrlRef.current}/meeting/meetingSpaceShare/${meetingMoid}`
			} else {
				setErrorMsg(t('提取码错误，请重新输入！'))
			}
		})
	}
	const onCancel = async () => {
		const preUrl = await fetchGetPlatformServiceUrl()
		window.location.href = `${preUrl}/meetingList.html`
	}
	return (
		<>
			<WebRecommendBrowser />
			<Header />
			<StyledExtractCodeWrap>
				<div className="title">{t('提取码')}</div>
				<div className="wrap" onMouseOver={() => setIsShowEye(true)} onMouseLeave={() => setIsShowEye(false)}>
					<Password
						className="extract-code-input"
						showEye={isShowEye}
						maxLength={128}
						width={300}
						placeholder={t('请输入提取码')}
						textAlign="center"
						value={code}
						validateMsg={<div className="error-msg">{errorMsg}</div>}
						onChange={(e, value) => onChange(value.trim())}
					/>
				</div>
				<Space space={5}>
					<Button onClick={() => onOk()}>{t('确定')}</Button>
					<Button onClick={() => onCancel()}>{t('取消')}</Button>
				</Space>
			</StyledExtractCodeWrap>
		</>
	)
}
export default App
